package com.yecheng.yeaiagent.app;

import com.yecheng.yeaiagent.advisor.MyLoggerAdvisor;
import com.yecheng.yeaiagent.chatmemory.FileBasedChatMemory;
import com.yecheng.yeaiagent.tools.WebSearchTools;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Component
@Slf4j
public class LoveApp {

    private final ChatClient chatClient;

    private static final String SYSTEM_PROMPT = "扮演深耕恋爱心理领域的专家。开场向用户表明身份，告知用户可倾诉恋爱难题。\" +\n" +
            "\"围绕单身、恋爱、已婚三种状态提问：单身状态询问社交圈拓展及追求心仪对象的困扰；\" +\n" +
            "\"恋爱状态询问沟通、习惯差异引发的矛盾；已婚状态询问家庭责任与亲属关系处理的问题。\" +\n" +
            "\"引导用户详述事情经过、对方反应及自身想法，以便给出专属解决方案。";

//    @Resource
//    private VectorStore LoveAppVectorStore;

    @Resource
    private Advisor loveAppRagCloudAdvisor;

    @Resource
    private ToolCallback[] allTools;

    @Resource
    private ToolCallbackProvider toolCallbackProvider;

    public record LoveReport(String title, List<String> suggestions) {
    }

    public LoveApp(ChatModel dashboardChatModel){
//        ChatMemory chatMemory = new InMemoryChatMemory();
        String fileDir = System.getProperty("user.dir") + "/chat-memory";
        FileBasedChatMemory chatMemory = new FileBasedChatMemory(fileDir);
        this.chatClient = ChatClient.builder(dashboardChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory)
                        ,new MyLoggerAdvisor())
                //,new ReReadingAdvisor())
                .build();
    }

    public Flux<String> doChatByStream(String msg,String chatID){
        return chatClient
                .prompt()
                .user(msg)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatID)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .tools(allTools)
                .stream()
                .content();
    }

    /**
     * 与用户对话
     * @param msg
     * @param chatID
     * @return
     */
    public String doChat(String msg,String chatID){
        ChatResponse response = chatClient
                .prompt()
                .user(msg)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatID)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        log.info("response:{}",response);
        return response.getResult().getOutput().getText();
    }

    /**
     * 与用户对话并生成恋爱报告
     * @param msg
     * @param chatID
     * @return
     */
    public LoveReport ChatWithReport(String msg,String chatID){
        LoveReport loveReport = chatClient
                .prompt()
                .system(SYSTEM_PROMPT + "每次对话后都要生成恋爱结果，标题为{用户名}的恋爱报告，内容为建议列表")
                .user(msg)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatID)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .entity(LoveReport.class);
        log.info("loveReport:{}",loveReport);
        return loveReport;
    }

    public String ChatWithRag(String msg,String chatID){
        String result = chatClient.prompt()
                .user(msg)
                .advisors(advisorSpec -> {
                    advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatID)
                            .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10);
                })
//                .advisors(new QuestionAnswerAdvisor(LoveAppVectorStore))
                .advisors(loveAppRagCloudAdvisor)
                .call()
                .chatResponse().getResult().getOutput().getText();
        log.info("result:{}",result);
        return result;
    }

    public String ChatWithWebSearch(String msg,String chatID){
        String result = chatClient.prompt()
                .user(msg)
                .advisors(advisorSpec -> {
                    advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatID)
                            .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10);
                })
                .system("你是一个专业的网络搜索助手")
                .tools(new WebSearchTools("4k5exAgWweS1dY2vXoYwH2Sg"))
                .call()
                .chatResponse().getResult().getOutput().getText();
        log.info("result:{}",result);
        return result;
    }

    public String ChatWithTools(String msg,String chatID){
        String text = chatClient.prompt()
                .user(msg)
                .advisors(advisorSpec -> {
                    advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatID)
                            .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10);
                })
                .tools(allTools)
                .call()
                .chatResponse().getResult().getOutput().getText();
        log.info("text:{}",text);
        return text;
    }

    public String ChatWithApp(String msg,String chatID){
        String text = chatClient.prompt()
                .user(msg)
                .advisors(advisorSpec -> {
                    advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatID)
                            .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10);
                })
                .advisors(loveAppRagCloudAdvisor)
                .tools(allTools)
                .tools(toolCallbackProvider)
                .call()
                .chatResponse().getResult().getOutput().getText();
        log.info("text:{}",text);
        return text;
    }
}
